﻿using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Reflection;
using System.Linq;
using System.Web;
using System.IO;


namespace Blog1._0.Data
{
    /// <summary>
    /// 数据库上下文
    /// </summary>
    public class SqlServerDbContext : DbContext, IDbContext
    {
        #region 构造函数
        /// <summary>
        /// 初始化一个 使用指定数据连接名称或连接串 的数据访问上下文类 的新实例
        /// </summary>
        /// <param name="connString"></param>
        public SqlServerDbContext(string connString)
            : base(connString)
        {
            this.Configuration.AutoDetectChangesEnabled = false;//自动跟踪对象的属性变化，默认为true
            this.Configuration.ValidateOnSaveEnabled = false;//保存前验证对象的属性最大最小长度等，默认为true。
            this.Configuration.LazyLoadingEnabled = false;//延迟加载，默认为true
            this.Configuration.ProxyCreationEnabled = false;//追踪
        }
        #endregion

        #region 重载
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            string assembleFileName = Assembly.GetExecutingAssembly().CodeBase.Replace("Blog1.0.Data.DLL", "Blog1.0.Mapping.dll").Replace("file:///", "");
            Assembly asm = Assembly.LoadFile(assembleFileName);
            var typesToRegister = asm.GetTypes()
            .Where(type => !String.IsNullOrEmpty(type.Namespace))
            .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }
            base.OnModelCreating(modelBuilder);

            //配置数据权限(全局过滤)
           // modelBuilder.Filter("BI_E", (BI_E b, int a) => (b == a),() => false);

        }
        #endregion


    }
}
